/*
 * @version: 1.0
 * @Author: zhl
 * @Date: 2021-09-18 09:43:48
 * @LastEditors: zhl
 * @LastEditTime: 2021-09-26 18:03:08
 * @Description: 文件实现描述
 */
#ifndef __COMMON_BASE64_H__
#define __COMMON_BASE64_H__


#include <string.h>
#include <openssl/pem.h>


static int base64_encode(char *str,int str_len,char *encode,int encode_len){
    BIO *bmem,*b64;
    BUF_MEM *bptr;
    b64=BIO_new(BIO_f_base64());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    bmem=BIO_new(BIO_s_mem());
    b64=BIO_push(b64,bmem);
    BIO_write(b64,str,str_len); //encode
    BIO_flush(b64);
    BIO_get_mem_ptr(b64,&bptr);
    if((int)(bptr->length) > encode_len){
        printf("encode_len too small\n");
        return -1; 
    }   
    encode_len=bptr->length;
    memcpy(encode,bptr->data,bptr->length);
    BIO_free_all(b64);
    return encode_len;
}
//
static int base64_decode(char *str,int str_len,char *decode,int decode_buffer_len){
    int len=0;
    BIO *b64,*bmem;
    b64=BIO_new(BIO_f_base64());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    bmem=BIO_new_mem_buf(str,str_len);
    bmem=BIO_push(b64,bmem);
    len=BIO_read(bmem,decode,str_len);
    decode[len]=0;
    BIO_free_all(bmem);
    return len;
}

static int get_base64_len(int len){
    if(0 == (len%3)){
        return (len/3)*4;
    }else {
        return (len/3+1)*4;
    }
}

#endif /* __COMMON_BASE64_H__ */